package com.nongtai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nongtai.constant.RedisConstant;
import com.nongtai.mapper.GoodsCategoryMapper;
import com.nongtai.mapper.GoodsMapper;
import com.nongtai.pojo.entity.Goods;
import com.nongtai.pojo.entity.GoodsCategory;
import com.nongtai.pojo.vo.GoodsCategoryVo;
import com.nongtai.pojo.vo.GoodsVo;
import com.nongtai.pojo.vo.SubCategoryVo;
import com.nongtai.result.Result;
import com.nongtai.service.GoodsCategoryService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 首页数据相关业务
 *
 * @author yza
 * @version 1.0
 * @date 2024/6/2 10:28
 */
@Service
public class GoodsCategoryServiceImpl implements GoodsCategoryService {
    @Resource
    private GoodsCategoryMapper goodsCategoryMapper;
    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 获取分类数据
     * 做缓存
     *
     * @return
     */
    @Cacheable(cacheNames = "front", key = "'goodsCategory'")
    public List<GoodsCategoryVo> getGoodsCategoryList() {
        // 查询所有商品分类数据
        List<GoodsCategory> goodsCategories = goodsCategoryMapper.selectList(null);

        // 根据所有数据构建树形结构的分类
        // goodsCategoryVoList集合中的每一个元素是一级分类,每一个一级分类里有多个子分类,子分类还可以有子分类
        List<GoodsCategoryVo> goodsCategoryVoList = buildCategoryTree(goodsCategories);

        return goodsCategoryVoList;
    }


    /**
     * 根基分类id获取分类信息
     * @param id 商品分类id
     * @return
     */
    @Override
    public GoodsCategoryVo getCategoryById(Long id) {
        // 根据分类id查找到的分类
        GoodsCategory goodsCategory = goodsCategoryMapper.selectByPrimaryKey(id);
        GoodsCategoryVo goodsCategoryVo = convertToVo(goodsCategory);

        // 组装该分类的子分类

        // 查询该分类的子分类
        QueryWrapper<GoodsCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        List<GoodsCategory> goodsCategories = goodsCategoryMapper.selectList(queryWrapper);

        // 组装
        List<GoodsCategoryVo> children = goodsCategoryVo.getChildren();
        for (GoodsCategory category : goodsCategories){
            GoodsCategoryVo categoryVo = convertToVo(category);
            children.add(categoryVo);
        }

        return goodsCategoryVo;
    }

    /**
     * 根据二级分类id查找该分类信息和其父分类信息
     * 将该二级分类下的所有商品查出
     * @param id
     * @return
     */
    @Override
    public SubCategoryVo getSubCategoryById(Long id) {
        // 查找该id的二级分类信息
        SubCategoryVo subCategoryVo = goodsCategoryMapper.selectSubCategoryById(id);
        // 装配其包含的商品信息
        List<GoodsVo> subCategoryVoGoods = subCategoryVo.getGoods();
        // 查找该分类下的所有商品
        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
        goodsQueryWrapper.eq("category_id_details",id);
        List<Goods> goodsList = goodsMapper.selectList(goodsQueryWrapper);
        // 为subCategoryVoGoods装配商品信息
        for(Goods goods : goodsList){
            GoodsVo goodsVo = new GoodsVo();
            BeanUtils.copyProperties(goods,goodsVo);
            subCategoryVoGoods.add(goodsVo);
        }

        return subCategoryVo;
    }

    /**
     * 通过所有的分类记录构建分类树形结构
     *
     * @param allCategories 所有的分类记录
     * @return 所有分类记录构成的vo对象树
     */
    private List<GoodsCategoryVo> buildCategoryTree(List<GoodsCategory> allCategories) {
        // 创建一个map用来通过id快速查找分类对象(vo)
        HashMap<Long, GoodsCategoryVo> categoryMap = new HashMap<>();

        // 将所有的实体类转换成vo加入到集合当中
        for (GoodsCategory goodsCategory : allCategories) {
            // 转成vo
            GoodsCategoryVo goodsCategoryVo = convertToVo(goodsCategory);
            // 将vo加入到map中
            categoryMap.put(goodsCategoryVo.getId(), goodsCategoryVo);
        }

        // 存放结果vo集合
        List<GoodsCategoryVo> categoryVoResList = new ArrayList<>();

        // 遍历所有分类，为它们设置子分类
        for (GoodsCategory category : allCategories) {
            Long parentId = category.getParentId();
            // 如果parentId不为空，把该对象加入到parent的children集合当中
            if (parentId != null && categoryMap.containsKey(parentId)) {
                // 从map中获取其父分类
                GoodsCategoryVo parent = categoryMap.get(parentId);
                // 把它加入到父分类的children集合中
                parent.getChildren().add(categoryMap.get(category.getId())); // 将当前分类设置为父分类的子分类

            } else {// parent_id为空，在categoryVoList里添加所有一级分类

                GoodsCategoryVo goodsCategoryVo = categoryMap.get(category.getId());

                // 将vo添加到总集合（分类树）当中
                categoryVoResList.add(goodsCategoryVo);
            }
        }

        return categoryVoResList;
    }

    /**
     * 使用BeanUtils将分类实体转换成vo对象用于传输
     *
     * @param goodsCategory
     * @return vo对象
     */
    private GoodsCategoryVo convertToVo(GoodsCategory goodsCategory) {
        GoodsCategoryVo goodsCategoryVo = new GoodsCategoryVo();
        BeanUtils.copyProperties(goodsCategory, goodsCategoryVo);
        return goodsCategoryVo;
    }


}
